#!/usr/bin/env ruby
require "fileutils"

@verbose = true

def list_patches()
	Dir.glob("patches/[0-9][0-9][0-9][0-9]-*").collect{|x| x[8..-1] }.sort
end
  
def list_applied_patches
	if File.exist?(".applied_patches")
		File.open(".applied_patches").collect{|x| x.strip!}
	else
		[]
	end
end

def apply_patches( patches_to_apply )
	f_applied = File.new( ".applied_patches", "a" )
	patches_to_apply.each do |patch|
		fn = File.join("patches",patch)
		content = File.open(fn).collect{|x| x.sub!("\n","\r\n") }
		#p content
		f = File.new( ".patch_to_apply", "wb" )
        f.write( content )
        f.close()
        fn = ".patch_to_apply"
		if system("patch -p0 < #{fn}")
			print "patch  #{patch} applied\n"
			f_applied.write(patch+"\n")
		end
		FileUtils.rm ".patch_to_apply"
	end
	f_applied.close()


end  
  
#p list_patches 
#p list_applied_patches 
apply_patches list_patches-list_applied_patches